package cn.conac.rc.gateway.security.service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import cn.conac.rc.framework.utils.ResultPojo;
import cn.conac.rc.framework.utils.StringUtils;
import cn.conac.rc.gateway.common.vo.AreaVo;
import cn.conac.rc.gateway.modules.common.service.AreaService;
import cn.conac.rc.gateway.modules.common.service.UserCommonService;
import cn.conac.rc.gateway.modules.common.vo.RoleVo;
import cn.conac.rc.gateway.modules.common.vo.UserVo;
import cn.conac.rc.gateway.modules.ofs.service.OrganizationReadService;
import cn.conac.rc.gateway.modules.ofs.service.OrganizationService;
import cn.conac.rc.gateway.modules.ofs.vo.OrganizationVo;
import cn.conac.rc.gateway.modules.user.service.UserService;
import cn.conac.rc.gateway.security.vo.JwtUser;

/**
 * Created by stephan on 20.03.16.
 */
@Service
public class JwtUserDetailsService implements UserDetailsService {
    @Autowired
    UserCommonService userCommonService;
    @Autowired
    UserService userService;
    @Autowired
    AreaService areaService;
    @Autowired
    OrganizationService organizationService;
    @Autowired
    OrganizationReadService organizationReadService;

    @Override
    public JwtUser loadUserByUsername(String userid) throws UsernameNotFoundException {
        String isMobileLogin = "";
        String isRepeat = "";
        if(userid.endsWith("_phone")){
            isMobileLogin = "1";//手机登录的时候不需要验证密码
            userid = userid.split("_")[0];
        }
        if(userid.endsWith("_repeat")){
            isRepeat = "1";//编制域名重复，输入身份证
            userid = userid.split("_")[0];
        }
        JSONObject result = userService.findByUserId(Integer.valueOf(userid));
        UserVo user = null;
        if (result.getString("code").equals(ResultPojo.CODE_SUCCESS) && result.getJSONObject("result")!=null) {
            user = result.getJSONObject("result").toJavaObject(UserVo.class);
        }

        if (user == null) {
            throw new UsernameNotFoundException(String.format("用户不存在"));
        } else {
            JwtUser jwtUser = new JwtUser(user);
            jwtUser.setAuthorities(mapToGrantedAuthorities(user.getRoleList()));
            if(StringUtils.isNotBlank(isMobileLogin)){
                //手机号码登录
                jwtUser.setIsMobileLogin("1");
            }
            if(StringUtils.isNotBlank(isRepeat)){
                //手机号码登录
                jwtUser.setIsRepeat("1");
            }
            try {
                // 取出部门信息
                if(StringUtils.isNotBlank(jwtUser.getOrgId())){
                    JSONObject result2 = organizationReadService.findById(jwtUser.getOrgId());
                    OrganizationVo org = new OrganizationVo();
                    BeanUtils.copyProperties(org, result2.get("result"));
                    if (org != null) {
                        jwtUser.setOrgBaseId(org.getBaseId());
                        jwtUser.setOrgName(org.getName());
                        jwtUser.setOrgSysType(org.getOwnSys());
                        jwtUser.setOrgType(org.getType());
                    }
                }
                
                
                // 取出地区信息
                ResultPojo result1 = areaService.detail(user.getAreaId());
                AreaVo area = new AreaVo();
                BeanUtils.copyProperties(area, result1.getResult());
                if (area != null) {
                    jwtUser.setAreaCode(area.getCode());
                    jwtUser.setIsTrialPoints(area.getType());
                    jwtUser.setAreaName(area.getName());
                    jwtUser.setAreaAdminCode(area.getAdminCode());
                    jwtUser.setAreaLvl(area.getLvl() + "");
                }
                
//                // TODO 过渡阶段 用户体系试点包头，黔东南
//                if (!(jwtUser.getAreaCode().startsWith("071280") //包头市
//                        || jwtUser.getAreaCode().startsWith("24361") //黔东南州
//                        || jwtUser.getAreaCode().startsWith("17258") //焦作
//                        || jwtUser.getAreaCode().startsWith("33000") //中央
//                        || jwtUser.getAreaCode().startsWith("24359") //黔西南州
//                        || jwtUser.getAreaCode().startsWith("07125") //巴彦淖尔
//                        || jwtUser.getAreaCode().startsWith("16240") //潍坊市
//                        )) {
//                    jwtUser.setIsComplete("0");
//                }
//                // TODO 过渡阶段 非编办用户不用完善信息
//                if(jwtUser.getUserType()!=1){
//                    jwtUser.setIsComplete("0");
//                }
                
                // 全国编办开放
                // 委办局对淮北开放
                jwtUser.setIsComplete("0");
                if (StringUtils.isBlank(user.getMobile())) {
                    if ("0".equals(jwtUser.getIsAdmin()) && jwtUser.getUsername().startsWith("rc_")) {
                        // 编制域名 且是导入的以“rc_”开头
                        if ("1".equals(jwtUser.getUserType() + "")) {
                            // 编办 全都算
                            jwtUser.setIsComplete("1");
                        } else if (jwtUser.getAreaCode().startsWith("13199")) {
                            // TODO 除了编办，针对淮北，开放委办局编制域名
                            jwtUser.setIsComplete("1");
                        }
                    }
                }
                
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return jwtUser;
        }
    }

    private static List<GrantedAuthority> mapToGrantedAuthorities(List<RoleVo> roles) {
        List<GrantedAuthority> list = new ArrayList<>(roles.size());
        for (RoleVo roleVo : roles) {
            list.add(new SimpleGrantedAuthority(roleVo.getId()));
        }
        return list;
    }

}
